const { Op, Sequelize } = require('sequelize');
const User = require('../models/User');
const Job = require('../models/job');
const Application = require('../models/Application');
const Company = require('../models/company');
const Resume = require('../models/resume');

// 获取数据统计信息
exports.getStatistics = async (req, res) => {
  try {
    // 用户统计
    const totalUsers = await User.count();
    const companyUsers = await User.count({ where: { role: 'company' } });
    const jobSeekerUsers = await User.count({ where: { role: 'job-seeker' } });
    const adminUsers = await User.count({ where: { role: 'admin' } });

    // 职位统计
    const totalJobs = await Job.count();
    const activeJobs = await Job.count({ where: { status: 'active' } });
    const pendingJobs = await Job.count({ where: { status: 'pending' } });

    // 企业统计
    const totalCompanies = await Company.count();
    const verifiedCompanies = await Company.count({ where: { status: 'approved' } });
    const pendingCompanies = await Company.count({ where: { status: 'pending' } });

    // 简历统计
    const totalResumes = await Resume.count();

    // 申请状态统计
    const pendingApplications = await Application.count({ where: { status: 'pending' } });
    const interviewApplications = await Application.count({ where: { status: 'interview_invited' } });
    const acceptedApplications = await Application.count({ where: { status: 'accepted' } });
    const rejectedApplications = await Application.count({ where: { status: 'rejected' } });

    // 投递统计
    const totalApplications = await Application.count();

    res.status(200).json({
      success: true,
      data: {
        users: {
          total: totalUsers,
          company: companyUsers,
          jobSeeker: jobSeekerUsers,
          admin: adminUsers
        },
        jobs: {
          total: totalJobs,
          active: activeJobs,
          pending: pendingJobs
        },
        companies: {
          total: totalCompanies,
          verified: verifiedCompanies,
          pending: pendingCompanies
        },
        resumes: {
          total: totalResumes
        },
        applications: {
          total: totalApplications,
          pending: pendingApplications,
          interview: interviewApplications,
          accepted: acceptedApplications,
          rejected: rejectedApplications
        },

      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取统计数据失败',
      error: error.message
    });
  }
};

// 获取行业分布统计
exports.getIndustryStats = async (req, res) => {
  try {
    // 职位行业分布
    const jobIndustry = await Job.findAll({
      attributes: [
        'industry',
        [Sequelize.fn('COUNT', Sequelize.col('id')), 'count']
      ],
      where: {
        status: 'active',
        industry: { [Op.not]: null }
      },
      group: ['industry'],
      order: [[Sequelize.col('count'), 'DESC']],
      limit: 10
    });

    // 企业行业分布
    const companyIndustry = await Company.findAll({
      attributes: [
        'industry',
        [Sequelize.fn('COUNT', Sequelize.col('id')), 'count']
      ],
      where: {
        status: 'approved',
        industry: { [Op.not]: null }
      },
      group: ['industry'],
      order: [[Sequelize.col('count'), 'DESC']],
      limit: 10
    });

    res.status(200).json({
      success: true,
      data: {
        jobIndustry,
        companyIndustry
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取行业分布数据失败',
      error: error.message
    });
  }
};

// 获取薪资范围统计
exports.getSalaryStats = async (req, res) => {
  try {
    const salaryRanges = [
      '3k以下', '3k-5k', '5k-8k', '8k-12k', '12k-15k',
      '15k-20k', '20k-30k', '30k-50k', '50k以上'
    ];

    // 构建薪资范围查询
    const salaryQueries = salaryRanges.map(range => {
      let whereClause;
      switch(range) {
        case '3k以下':
          whereClause = { [Op.lt]: 3000 };
          break;
        case '3k-5k':
          whereClause = { [Op.between]: [3000, 5000] };
          break;
        case '5k-8k':
          whereClause = { [Op.between]: [5000, 8000] };
          break;
        case '8k-12k':
          whereClause = { [Op.between]: [8000, 12000] };
          break;
        case '12k-15k':
          whereClause = { [Op.between]: [12000, 15000] };
          break;
        case '15k-20k':
          whereClause = { [Op.between]: [15000, 20000] };
          break;
        case '20k-30k':
          whereClause = { [Op.between]: [20000, 30000] };
          break;
        case '30k-50k':
          whereClause = { [Op.between]: [30000, 50000] };
          break;
        case '50k以上':
          whereClause = { [Op.gt]: 50000 };
          break;
      }

      return Job.count({
        where: {
          status: 'active',
          salaryMin: whereClause
        }
      }).then(count => ({ range, count }));
    });

    // 并行执行所有查询
    const salaryStats = await Promise.all(salaryQueries);

    res.status(200).json({
      success: true,
      data: salaryStats
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取薪资范围数据失败',
      error: error.message
    });
  }
};

// 获取近期数据趋势
exports.getTrends = async (req, res) => {
  try {
    const days = parseInt(req.query.days) || 7;
    const endDate = new Date();
    const startDate = new Date();
    startDate.setDate(startDate.getDate() - days);

    // 按日期统计新用户
    const userTrends = await User.findAll({
      attributes: [
        [Sequelize.fn('DATE', Sequelize.col('createdAt')), 'date'],
        [Sequelize.fn('COUNT', Sequelize.col('id')), 'count']
      ],
      where: {
        createdAt: {
          [Op.between]: [startDate, endDate]
        }
      },
      group: ['date'],
      order: [[Sequelize.fn('DATE', Sequelize.col('createdAt')), 'ASC']]
    });

    // 按日期统计新职位
    const jobTrends = await Job.findAll({
      attributes: [
        [Sequelize.fn('DATE', Sequelize.col('createdAt')), 'date'],
        [Sequelize.fn('COUNT', Sequelize.col('id')), 'count']
      ],
      where: {
        createdAt: {
          [Op.between]: [startDate, endDate]
        }
      },
      group: ['date'],
      order: [[sequelize.fn('DATE', sequelize.col('createdAt')), 'ASC']]
    });

    res.status(200).json({
      success: true,
      data: {
        userTrends,
        jobTrends
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取趋势数据失败',
      error: error.message
    });
  }
};